<template>
<div :class="[$style.container]">
<el-form size="small" label-position="top" :rules="rules" :model="form" @submit.native.prevent="" ref="fm">
  <el-form-item prop="api" label="文档服务地址">
    <el-input v-model="form.api" placeholder="例如：http://127.0.0.1:8001"></el-input>
  </el-form-item>
  <el-form-item prop="previewUrl" label="预览服务地址">
    <el-input v-model="form.previewUrl" placeholder="例如：http://127.0.0.1:8003"></el-input>
  </el-form-item>
</el-form>
<div class="text-center">
  <el-button size="small" type="primary" @click="onConfirm" :loading="submitting" class="px-5">保存应用设置</el-button>
</div>
</div>
</template>

<script lang="ts">

import { getInitOptions, setInitOptions } from '@/config/init'
import { Vue, Component, Prop, Emit, Ref } from 'vue-property-decorator'

@Component
export default class ServerSetting extends Vue {
  @Ref() fm!: any

  submitting = false

  form = {
    api: '',
    previewUrl: ''
  }

  rules = {
    api: [
      { required: true, message: '请输入文档服务地址', trigger: 'change' }
    ],
    previewUrl: [
      { required: true, message: '请输入预览服务地址', trigger: 'change' }
    ]
  }

  initForm () {
    const c = getInitOptions()
    this.form = {
      api: c?.api || '',
      previewUrl: c?.previewUrl || ''
    }
  }

  onConfirm () {
    this.fm.validate().then((valid: boolean) => {
      if (!valid) return
      localStorage.removeItem('jwt_token')
      localStorage.removeItem('token')
      setInitOptions(this.form)
      this.refresh()
    })
  }

  refresh () {
    this.$http.inst.defaults.baseURL = getInitOptions().api
    this.$router.push('/login')
    window.location.reload()
  }

  created () {
    this.initForm()
  }
}
</script>

<style lang="scss" module>
@import "~@/styles/vars.scss";

.container {

}
</style>
